'use client'

import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconEye, IconEyeOff, IconLock, IconShield, IconCheck, IconX } from "@tabler/icons-react"
import { api } from '@/lib/api'
import { PasswordCrypto } from '@/lib/crypto'
import { toast } from 'sonner'

interface PasswordManagerProps {
  onClose?: () => void
  className?: string
}

export default function PasswordManager({ onClose, className = '' }: PasswordManagerProps) {
  const [formData, setFormData] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  const [showPasswords, setShowPasswords] = useState({
    old: false,
    new: false,
    confirm: false
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  
  // 密码强度检查
  const [passwordStrength, setPasswordStrength] = useState<{
    strong: boolean
    score: number
    suggestions: string[]
  } | null>(null)

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    
    // 实时检查新密码强度
    if (name === 'newPassword' && value) {
      setPasswordStrength(PasswordCrypto.checkPasswordStrength(value))
    } else if (name === 'newPassword' && !value) {
      setPasswordStrength(null)
    }
    
    // 清除错误信息
    if (error) setError('')
    if (success) setSuccess('')
  }

  const togglePasswordVisibility = (field: 'old' | 'new' | 'confirm') => {
    setShowPasswords(prev => ({
      ...prev,
      [field]: !prev[field]
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 验证
    if (!formData.oldPassword || !formData.newPassword || !formData.confirmPassword) {
      setError('请填写所有密码字段')
      return
    }
    
    if (formData.newPassword !== formData.confirmPassword) {
      setError('新密码和确认密码不匹配')
      return
    }
    
    if (formData.newPassword.length < 6) {
      setError('新密码长度至少为6个字符')
      return
    }
    
    if (formData.oldPassword === formData.newPassword) {
      setError('新密码不能与旧密码相同')
      return
    }

    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      await api.auth.changePassword(formData.oldPassword, formData.newPassword)
      
      setSuccess('密码修改成功！请重新登录')
      toast.success('密码修改成功', {
        description: '请使用新密码重新登录'
      })
      
      // 清空表单
      setFormData({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      setPasswordStrength(null)
      
      // 3秒后关闭组件
      setTimeout(() => {
        if (onClose) onClose()
      }, 3000)
      
    } catch (err: any) {
      console.error('修改密码失败:', err)
      
      let errorMessage = '修改密码失败，请稍后重试'
      if (err.response?.data?.message) {
        errorMessage = err.response.data.message
      } else if (err.message) {
        errorMessage = err.message
      }
      
      setError(errorMessage)
      toast.error('密码修改失败', {
        description: errorMessage
      })
    } finally {
      setIsLoading(false)
    }
  }

  const getPasswordStrengthColor = (score: number) => {
    if (score <= 2) return 'bg-red-500'
    if (score <= 3) return 'bg-yellow-500'
    return 'bg-green-500'
  }

  const getPasswordStrengthText = (score: number) => {
    if (score <= 2) return '弱'
    if (score <= 3) return '中等'
    return '强'
  }

  return (
    <Card className={`w-full max-w-md mx-auto ${className}`}>
      <CardHeader className="text-center pb-4">
        <div className="flex items-center justify-center gap-2 mb-2">
          <IconShield className="w-6 h-6 text-blue-600" />
          <CardTitle className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            修改密码
          </CardTitle>
        </div>
        <CardDescription className="text-gray-600 dark:text-gray-400">
          使用bcrypt加密保护您的新密码
        </CardDescription>
      </CardHeader>
      
      <CardContent className="space-y-4">
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* 旧密码 */}
          <div className="space-y-2">
            <Label htmlFor="oldPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
              当前密码
            </Label>
            <div className="relative">
              <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                id="oldPassword"
                name="oldPassword"
                type={showPasswords.old ? 'text' : 'password'}
                value={formData.oldPassword}
                onChange={handleInputChange}
                placeholder="请输入当前密码"
                className="pl-10 pr-10"
                disabled={isLoading}
                required
              />
              <button
                type="button"
                onClick={() => togglePasswordVisibility('old')}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                disabled={isLoading}
              >
                {showPasswords.old ? <IconEye className="w-4 h-4" /> : <IconEyeOff className="w-4 h-4" />}
              </button>
            </div>
          </div>

          {/* 新密码 */}
          <div className="space-y-2">
            <Label htmlFor="newPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
              新密码
            </Label>
            <div className="relative">
              <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                id="newPassword"
                name="newPassword"
                type={showPasswords.new ? 'text' : 'password'}
                value={formData.newPassword}
                onChange={handleInputChange}
                placeholder="请输入新密码"
                className="pl-10 pr-10"
                disabled={isLoading}
                required
              />
              <button
                type="button"
                onClick={() => togglePasswordVisibility('new')}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                disabled={isLoading}
              >
                {showPasswords.new ? <IconEye className="w-4 h-4" /> : <IconEyeOff className="w-4 h-4" />}
              </button>
            </div>
            
            {/* 密码强度指示 */}
            {passwordStrength && (
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <div className="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-1">
                    <div 
                      className={`h-1 rounded-full transition-all duration-300 ${getPasswordStrengthColor(passwordStrength.score)}`}
                      style={{ width: `${(passwordStrength.score / 5) * 100}%` }}
                    />
                  </div>
                  <span className={`text-xs ${
                    passwordStrength.strong ? 'text-green-600 dark:text-green-400' :
                    'text-yellow-600 dark:text-yellow-400'
                  }`}>
                    {getPasswordStrengthText(passwordStrength.score)}
                  </span>
                  {passwordStrength.strong ? 
                    <IconCheck className="w-3 h-3 text-green-600" /> :
                    <IconX className="w-3 h-3 text-yellow-600" />
                  }
                </div>
                {!passwordStrength.strong && passwordStrength.suggestions.length > 0 && (
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    建议：{passwordStrength.suggestions.slice(0, 2).join('、')}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* 确认密码 */}
          <div className="space-y-2">
            <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
              确认新密码
            </Label>
            <div className="relative">
              <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                id="confirmPassword"
                name="confirmPassword"
                type={showPasswords.confirm ? 'text' : 'password'}
                value={formData.confirmPassword}
                onChange={handleInputChange}
                placeholder="请再次输入新密码"
                className="pl-10 pr-10"
                disabled={isLoading}
                required
              />
              <button
                type="button"
                onClick={() => togglePasswordVisibility('confirm')}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                disabled={isLoading}
              >
                {showPasswords.confirm ? <IconEye className="w-4 h-4" /> : <IconEyeOff className="w-4 h-4" />}
              </button>
            </div>
            
            {/* 密码匹配指示 */}
            {formData.confirmPassword && (
              <div className="flex items-center gap-1 text-xs">
                {formData.newPassword === formData.confirmPassword ? (
                  <>
                    <IconCheck className="w-3 h-3 text-green-600" />
                    <span className="text-green-600 dark:text-green-400">密码匹配</span>
                  </>
                ) : (
                  <>
                    <IconX className="w-3 h-3 text-red-600" />
                    <span className="text-red-600 dark:text-red-400">密码不匹配</span>
                  </>
                )}
              </div>
            )}
          </div>

          {/* 错误提示 */}
          {error && (
            <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
              <AlertDescription className="text-red-700 dark:text-red-300">
                {error}
              </AlertDescription>
            </Alert>
          )}

          {/* 成功提示 */}
          {success && (
            <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
              <AlertDescription className="text-green-700 dark:text-green-300">
                {success}
              </AlertDescription>
            </Alert>
          )}

          {/* 按钮组 */}
          <div className="flex gap-3 pt-2">
            <Button
              type="submit"
              className="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white"
              disabled={isLoading || !passwordStrength?.strong || formData.newPassword !== formData.confirmPassword}
            >
              {isLoading ? (
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  修改中...
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <IconShield className="w-4 h-4" />
                  确认修改
                </div>
              )}
            </Button>
            
            {onClose && (
              <Button
                type="button"
                variant="outline"
                onClick={onClose}
                disabled={isLoading}
                className="px-6"
              >
                取消
              </Button>
            )}
          </div>
        </form>

        {/* 安全提示 */}
        <div className="text-center pt-4 border-t border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-center gap-2 text-xs text-gray-500 dark:text-gray-400">
            <IconShield className="w-3 h-3" />
            <span>密码采用bcrypt加密存储，确保安全</span>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}